import { SEO } from '@/utils/seo'
import ExifReader from 'exifreader'
import html2canvas from 'html2canvas'
import React, { useRef, useState } from 'react'
import styles from './index.less'

// 导入水印组件
import {
  BlurredImageWatermark,
  BottomBarWatermark,
  CenteredSquareWatermark,
  Standard2Watermark
} from './components'
import componentStyles from './components/watermark.less'

// 导入所有logo SVG
import AppleLogo from '@/assets/logo/apple-14.svg'
import AppleLogoWhite from '@/assets/logo/apple-white.svg'
import CanonLogo from '@/assets/logo/canon-logo.svg'
import DjiLogoBlack from '@/assets/logo/dji-black.svg'
import DjiLogoWhite from '@/assets/logo/dji-white.svg'
import FujifilmLogoBlack from '@/assets/logo/fujifilm-black.svg'
import FujifilmLogoWhite from '@/assets/logo/fujifilm-white.svg'
import HasselbladWhiteLogo from '@/assets/logo/hasselblad-white.svg'
import HasselbladLogo from '@/assets/logo/hasselblad.svg'
import HonorLogo from '@/assets/logo/honor-1.svg'
import HuaweiLogo from '@/assets/logo/huawei-2.svg'
import HuaweiLogo2 from '@/assets/logo/huawei.svg'
import LeicaLogo2 from '@/assets/logo/leica-logo.svg'
import LeicaLogo from '@/assets/logo/leica.svg'
import LG1Logo from '@/assets/logo/lg-1.svg'
import LGELLogo from '@/assets/logo/lg-electronics.svg'
import MeizuLogo from '@/assets/logo/meizu-logo-1.svg'
import NasaLogo from '@/assets/logo/nasa-6.svg'
import OlympusLogo from '@/assets/logo/olympus-2.svg'
import OneplusLogo from '@/assets/logo/oneplus-5.svg'
import PanasonicLogo from '@/assets/logo/panasonic-1.svg'
import PhaseOneLogo from '@/assets/logo/phase-one-logo.svg'
import RealmeLogo from '@/assets/logo/realme-2.svg'
import RealmeLogo2 from '@/assets/logo/realme-realme-logo-1.svg'
import RicohLogo from '@/assets/logo/ricoh-4.svg'
import RicohLogo2 from '@/assets/logo/ricoh-logo-2005-neu.svg'
import SamsungBlackLogo from '@/assets/logo/samsung-black.svg'
import SamsungBlueLogo from '@/assets/logo/samsung-blue.svg'
import SamsungWhiteLogo from '@/assets/logo/samsung-white.svg'
import SonyLogo from '@/assets/logo/sony-2.svg'
import TikTokLogo from '@/assets/logo/tiktok-icon-2.svg'
import VivoLogo from '@/assets/logo/vivo-1.svg'
import XiaomiLogo from '@/assets/logo/xiaomi-3.svg'

// SVG水印样式预览组件
const StylePreviewSVG = {
  // 标准水印样式
  style1: () => (
    <svg width="80" height="80" viewBox="0 0 80 80" xmlns="http://www.w3.org/2000/svg">
      <rect x="0" y="0" width="80" height="60" fill="#e1e7f5" />
      <rect x="0" y="60" width="80" height="20" fill="#333333" />

      {/* 左侧：logo和型号简化表示 */}
      <circle cx="12" cy="70" r="4" fill="#ffffff" />
      <rect x="20" y="69" width="15" height="2" fill="#ffffff" />

      {/* 右侧：参数信息简化表示 */}
      <rect x="55" y="69" width="15" height="2" fill="#ffffff" />
    </svg>
  ),
  // 方形边框样式
  style2: () => (
    <svg width="80" height="80" viewBox="0 0 80 80" xmlns="http://www.w3.org/2000/svg">
      <rect x="0" y="0" width="80" height="80" fill="#f5f5f5" />

      {/* 主要图片区域 */}
      <rect x="5" y="5" width="70" height="55" fill="#e1e7f5" />

      {/* 白色方形边框 - 降低高度 */}
      <rect x="10" y="10" width="60" height="45" fill="white" stroke="#333" strokeWidth="1" />

      {/* 品牌logo和参数信息区域 - 垂直排列，logo在上方，参数在下方 */}
      <circle cx="40" cy="63" r="3" fill="#333" />
      <rect x="30" y="69" width="20" height="2" fill="#333" />
    </svg>
  ),
  // 模糊背景样式
  style3: () => (
    <svg width="80" height="80" viewBox="0 0 80 80" xmlns="http://www.w3.org/2000/svg">
      <defs>
        <linearGradient id="blurGradient" x1="0%" y1="0%" x2="100%" y2="100%">
          <stop offset="0%" stopColor="#ff7e7e" />
          <stop offset="20%" stopColor="#ffda7e" />
          <stop offset="40%" stopColor="#c3ff7e" />
          <stop offset="60%" stopColor="#7effda" />
          <stop offset="80%" stopColor="#7e9cff" />
          <stop offset="100%" stopColor="#da7eff" />
        </linearGradient>
      </defs>

      <rect x="0" y="0" width="80" height="80" fill="#d5e8f5" />

      {/* 主要图片区域 */}
      <rect x="5" y="5" width="70" height="55" fill="#e1e7f5" />

      {/* 彩虹渐变边框表示模糊效果 */}
      <rect
        x="10"
        y="10"
        width="60"
        height="45"
        fill="transparent"
        stroke="url(#blurGradient)"
        strokeWidth="2"
        opacity="0.8"
      />

      {/* 品牌logo和参数信息区域 - 垂直排列，logo在上方，参数在下方 */}
      <circle cx="40" cy="63" r="3" fill="#333" />
      <rect x="30" y="69" width="20" height="2" fill="#333" />
    </svg>
  ),
  // 富士胶片样式
  style4: () => (
    <svg width="80" height="80" viewBox="0 0 80 80" xmlns="http://www.w3.org/2000/svg">
      <defs>
        <linearGradient id="fujiGradient" x1="0%" y1="0%" x2="100%" y2="100%">
          <stop offset="0%" stopColor="#95cfed" />
          <stop offset="100%" stopColor="#0053ae" />
        </linearGradient>
      </defs>

      {/* 主要图片区域 */}
      <rect x="0" y="0" width="80" height="80" fill="#f5f5f5" />
      <rect x="5" y="5" width="70" height="55" fill="#e1e7f5" />

      {/* 边框 */}
      <rect x="10" y="10" width="60" height="45" fill="transparent" stroke="#333" strokeWidth="1" />

      {/* 标准水印 */}
      <rect x="10" y="60" width="60" height="15" fill="white" />

      {/* 信息元素 - 参数在左，logo在右 */}
      <rect x="15" y="67" width="20" height="2" fill="#333" />
      <circle cx="65" cy="67" r="3" fill="url(#fujiGradient)" />

      {/* 富士特征的右侧蓝色渐变条 */}
      <rect x="75" y="10" width="2" height="60" fill="url(#fujiGradient)" />
    </svg>
  )
}

type WaterMarkType = {
  brand: string
  backgroundColor: string
  fontSize: number
  dateFormat: string
  logoPosition: 'left' | 'center' | 'right'
  exifData: {
    make: string
    model: string
    focalLength: string
    aperture: string
    shutterSpeed: string
    iso: string
  }
  watermarkHeight: number // 水印高度（像素）
  watermarkStyle: 'style1' | 'style2' | 'style3' | 'style4' // 水印样式
  lensInfo?: string // 镜头信息
  dateTime?: string // 拍摄日期时间
  customText?: string // 自定义文字
  // 显示开关
  showModel?: boolean
  showAperture?: boolean
  showShutter?: boolean
  showISO?: boolean
  showFocalLength?: boolean
  showLensInfo?: boolean
  showDateTime?: boolean
}

// 默认机型配置
const deviceModels: Record<string, string> = {
  'apple-1': 'iPhone 16 Pro',
  'apple-2': 'iPhone 16 Pro',
  'canon-logo': 'EOS R5',
  'dji-1': 'Mavic 3',
  'dji-2': 'Mavic 3',
  'fujifilm-1': 'X-T5',
  'fujifilm-2': 'X-T5',
  hasselblad: 'X2D 100C',
  'hasselblad-white': 'X2D 100C',
  'honor-1': 'Magic 6 Pro',
  'huawei-2': 'Mate60 Pro',
  huawei: 'Mate60 Pro',
  leica: 'M11',
  'leica-logo': 'M11',
  'lg-1': 'LG G8',
  'lg-electronics': 'LG V60',
  'meizu-logo-1': 'Meizu 20 Pro',
  'nasa-6': 'NASA Cam',
  'olympus-2': 'OM-1',
  'oneplus-5': 'OnePlus 12',
  'panasonic-1': 'Lumix S5 II',
  'phase-one-logo': 'Phase One XF',
  'realme-2': 'GT 5 Pro',
  'realme-realme-logo-1': 'GT 5 Pro',
  'ricoh-4': 'GR III',
  'ricoh-logo-2005-neu': 'GR III',
  'samsung-1': 'Galaxy S24 Ultra',
  'samsung-2': 'Galaxy S24 Ultra',
  'samsung-3': 'Galaxy S24 Ultra',
  'sony-2': 'Alpha 7R V',
  'tiktok-icon-2': 'TikTok Cam',
  'vivo-1': 'X100 Pro',
  'xiaomi-3': 'Xiaomi 14 Ultra'
}

const WaterMark = () => {
  const imageContainerRef = useRef<HTMLDivElement>(null)
  const [image, setImage] = useState<string | null>(null)
  const [imageSize, setImageSize] = useState({ width: 0, height: 0 })
  const [exifFound, setExifFound] = useState(false)
  const [watermark, setWatermark] = useState<WaterMarkType>({
    brand: 'sony-2',
    backgroundColor: 'black',
    fontSize: 24,
    dateFormat: 'YYYY-MM-DD',
    logoPosition: 'left',
    exifData: {
      make: '',
      model: '',
      focalLength: '',
      aperture: '',
      shutterSpeed: '',
      iso: ''
    },
    watermarkHeight: 70,
    watermarkStyle: 'style1',
    lensInfo: '',
    dateTime: '',
    customText: '',
    showModel: true,
    showAperture: true,
    showShutter: true,
    showISO: true,
    showFocalLength: true,
    showLensInfo: true,
    showDateTime: true
  })
  // 新增：外观面板的边距em单位
  const [paddingEm, setPaddingEm] = useState(1)
  // 新增：style2 字体比例百分比
  const [fontSizeRatio, setFontSizeRatio] = useState(1)
  // 新增：style1 logo大小比例百分比
  const [logoSizeRatio, setLogoSizeRatio] = useState(1)

  // 水印样式列表
  const watermarkStyles = [
    {
      value: 'style1',
      label: '标准风格1', // Corresponds to BottomBarWatermark
      preview: StylePreviewSVG.style1,
      description: '底部带品牌和拍摄参数的信息栏'
    },
    {
      value: 'style4',
      label: '标准风格2', // Corresponds to Standard2Watermark
      preview: StylePreviewSVG.style4,
      description: '类似富士相机的简约渐变水印'
    },
    {
      value: 'style2',
      label: '方形边框',
      preview: StylePreviewSVG.style2,
      description: '白色方形边框，居中显示品牌和参数'
    },
    {
      value: 'style3',
      label: '模糊背景',
      preview: StylePreviewSVG.style3,
      description: '使用图片局部区域模糊处理作为背景'
    }
  ]

  // 从logo目录获取所有品牌
  const brands = [
    { value: '', label: '无', logo: '' },
    { value: 'apple-1', label: '苹果（黑）', logo: AppleLogo },
    { value: 'apple-2', label: '苹果（白）', logo: AppleLogoWhite },
    { value: 'canon-logo', label: '佳能', logo: CanonLogo },
    { value: 'dji-1', label: '大疆（黑）', logo: DjiLogoBlack },
    { value: 'dji-2', label: '大疆（白）', logo: DjiLogoWhite },
    { value: 'fujifilm-1', label: '富士(黑)', logo: FujifilmLogoBlack },
    { value: 'fujifilm-2', label: '富士(白)', logo: FujifilmLogoWhite },
    { value: 'hasselblad', label: '哈苏', logo: HasselbladLogo },
    { value: 'hasselblad-white', label: '哈苏(白)', logo: HasselbladWhiteLogo },
    { value: 'honor-1', label: '荣耀', logo: HonorLogo },
    { value: 'huawei-2', label: '华为', logo: HuaweiLogo },
    { value: 'huawei', label: '华为(2)', logo: HuaweiLogo2 },
    { value: 'leica', label: '徕卡', logo: LeicaLogo },
    { value: 'leica-logo', label: '徕卡(logo)', logo: LeicaLogo2 },
    { value: 'lg-1', label: 'LG', logo: LG1Logo },
    { value: 'lg-electronics', label: 'LG电子', logo: LGELLogo },
    { value: 'meizu-logo-1', label: '魅族', logo: MeizuLogo },
    { value: 'nasa-6', label: 'NASA', logo: NasaLogo },
    { value: 'olympus-2', label: '奥林巴斯', logo: OlympusLogo },
    { value: 'oneplus-5', label: '一加', logo: OneplusLogo },
    { value: 'panasonic-1', label: '松下', logo: PanasonicLogo },
    { value: 'phase-one-logo', label: 'Phase One', logo: PhaseOneLogo },
    { value: 'realme-2', label: 'Realme', logo: RealmeLogo },
    { value: 'realme-realme-logo-1', label: 'Realme(2)', logo: RealmeLogo2 },
    { value: 'ricoh-4', label: '理光', logo: RicohLogo },
    { value: 'ricoh-logo-2005-neu', label: '理光(2005)', logo: RicohLogo2 },
    { value: 'samsung-1', label: '三星(黑)', logo: SamsungBlackLogo },
    { value: 'samsung-2', label: '三星(白)', logo: SamsungWhiteLogo },
    { value: 'samsung-3', label: '三星(蓝)', logo: SamsungBlueLogo },
    { value: 'sony-2', label: '索尼', logo: SonyLogo },
    { value: 'tiktok-icon-2', label: 'TikTok', logo: TikTokLogo },
    { value: 'vivo-1', label: 'Vivo', logo: VivoLogo },
    { value: 'xiaomi-3', label: '小米', logo: XiaomiLogo }
  ]

  const backgroundColors = [
    { value: 'white', label: '白色' },
    { value: 'black', label: '黑色' },
    { value: '#f5f5f5', label: '浅灰色' },
    { value: '#333333', label: '深灰色' }
  ]

  // 读取EXIF信息
  const readExifData = async (file: File) => {
    try {
      const arrayBuffer = await file.arrayBuffer()
      const tags = ExifReader.load(arrayBuffer)

      console.log('EXIF Tags:', tags)

      if (tags) {
        // 提取相机品牌和型号
        const make = tags.Make?.description || ''
        const model = tags.Model?.description || ''

        // 提取焦距、光圈、快门速度和ISO
        const focalLength = tags.FocalLength?.description || ''
        const aperture = tags.FNumber?.description || ''
        const shutterSpeed = tags.ExposureTime?.description
          ? `${tags.ExposureTime.description}s`
          : ''
        const iso = tags.ISOSpeedRatings?.description
          ? `ISO${tags.ISOSpeedRatings.description}`
          : ''

        // 根据品牌名称匹配到品牌列表中的项目
        let matchedBrand = 'huawei-2' // 默认品牌

        if (make) {
          const lowerMake = make.toLowerCase()

          if (lowerMake.includes('huawei')) matchedBrand = 'huawei-2'
          else if (lowerMake.includes('apple') || lowerMake.includes('iphone'))
            matchedBrand = 'apple-1'
          else if (lowerMake.includes('xiaomi')) matchedBrand = 'xiaomi-3'
          else if (lowerMake.includes('samsung')) matchedBrand = 'samsung-1'
          else if (lowerMake.includes('honor')) matchedBrand = 'honor-1'
          else if (lowerMake.includes('vivo')) matchedBrand = 'vivo-1'
          else if (lowerMake.includes('oneplus')) matchedBrand = 'oneplus-5'
          else if (lowerMake.includes('sony')) matchedBrand = 'sony-2'
          else if (lowerMake.includes('canon')) matchedBrand = 'canon-logo'
          else if (lowerMake.includes('leica')) matchedBrand = 'leica'
          else if (lowerMake.includes('fuji')) matchedBrand = 'fujifilm-1'
          else if (lowerMake.includes('hasselblad')) matchedBrand = 'hasselblad'
          else if (lowerMake.includes('olympus')) matchedBrand = 'olympus-2'
          else if (lowerMake.includes('panasonic')) matchedBrand = 'panasonic-1'
          else if (lowerMake.includes('ricoh')) matchedBrand = 'ricoh-4'
          else if (lowerMake.includes('dji')) matchedBrand = 'dji-1'
          else if (lowerMake.includes('meizu')) matchedBrand = 'meizu-logo-1'
          else if (lowerMake.includes('realme')) matchedBrand = 'realme-2'
          else if (lowerMake.includes('lg')) matchedBrand = 'lg-1'
          else if (lowerMake.includes('phase')) matchedBrand = 'phase-one-logo'
          else if (lowerMake.includes('nasa')) matchedBrand = 'nasa-6'
          else if (lowerMake.includes('tiktok')) matchedBrand = 'tiktok-icon-2'
        }

        setWatermark((prev) => ({
          ...prev,
          brand: matchedBrand,
          exifData: {
            make,
            model,
            focalLength,
            aperture,
            shutterSpeed,
            iso
          },
          lensInfo:
            tags.LensModel?.description ||
            tags.Lens?.description ||
            `${tags.Make?.description || ''} ${tags.Model?.description || ''}`,
          dateTime: tags.DateTimeOriginal?.description || tags.DateTime?.description || ''
        }))

        setExifFound(true)
        return true
      }
    } catch (error) {
      console.error('Error reading EXIF data:', error)
    }

    setExifFound(false)
    return false
  }

  const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) {
      // 检查文件大小是否超过50MB
      const maxSize = 50 * 1024 * 1024 // 50MB
      if (file.size > maxSize) {
        alert('图片大小不能超过50MB，请选择较小的图片')
        return
      }

      // 尝试读取EXIF数据
      await readExifData(file)

      // 转换为base64显示图片
      const reader = new FileReader()
      reader.onload = (event) => {
        setImage(event.target?.result as string)

        // 获取图片尺寸
        const img = new Image()
        img.onload = () => {
          setImageSize({ width: img.width, height: img.height })
        }
        img.src = event.target?.result as string
      }
      reader.readAsDataURL(file)
    }
  }

  const handleExport = () => {
    if (!imageContainerRef.current) return

    html2canvas(imageContainerRef.current, {
      useCORS: true,
      allowTaint: true,
      backgroundColor: null,
      scale: 2 // 使用更高的缩放比例以获得更清晰的图像
    }).then((canvas) => {
      const link = document.createElement('a')
      link.download = 'watermarked-image.png'
      link.href = canvas.toDataURL('image/png')
      link.click()
    })
  }

  // 获取当前品牌信息
  const getCurrentBrand = () => {
    return brands.find((b) => b.value === watermark.brand) || brands[0]
  }

  // 根据背景色获取文字颜色
  const getTextColor = () => {
    // 白底或浅灰色底使用黑色文字，其他情况使用白色文字
    return ['white', '#f5f5f5'].includes(watermark.backgroundColor) ? 'black' : 'white'
  }

  // 获取机型（只显示型号，不拼接品牌）
  const getDeviceModel = () => {
    // 优先用EXIF
    if (exifFound && watermark.exifData.model) {
      return watermark.exifData.model
    }
    // 否则用预设
    return deviceModels[watermark.brand] || ''
  }

  // 渲染水印组件
  const renderWatermark = () => {
    if (!image) return null

    const commonProps = {
      image,
      watermarkConfig: { ...watermark, customText: watermark.customText ?? '' },
      brandLogo: getCurrentBrand().logo,
      brandLabel: getCurrentBrand().label,
      deviceModel: getDeviceModel(),
      textColor: getTextColor(),
      imageSize,
      containerRef: imageContainerRef,
      fontSizeRatio // 统一传递
    }

    switch (watermark.watermarkStyle) {
      case 'style4':
        return (
          <Standard2Watermark
            {...commonProps}
            textColor={getTextColor()}
            logoSizeRatio={logoSizeRatio}
            paddingEm={paddingEm}
          />
        )
      case 'style2':
        return (
          <CenteredSquareWatermark
            {...commonProps}
            paddingEm={paddingEm}
            logoSizeRatio={logoSizeRatio}
          />
        )
      case 'style3':
        return <BlurredImageWatermark {...commonProps} paddingEm={paddingEm} />
      case 'style1':
      default:
        return <BottomBarWatermark {...commonProps} logoSizeRatio={logoSizeRatio} />
    }
  }

  // 创建缩略图样式选择器
  const renderStyleSelector = () => {
    return (
      <div className={componentStyles.watermarkStyleSelector}>
        {watermarkStyles.map((style) => {
          const PreviewComponent = style.preview
          return (
            <div
              key={style.value}
              className={`${componentStyles.styleOption} ${
                watermark.watermarkStyle === style.value ? componentStyles.styleOptionActive : ''
              }`}
              onClick={() => {
                if (style.value === 'style3') {
                  setWatermark({
                    ...watermark,
                    watermarkStyle: style.value as 'style1' | 'style2' | 'style3' | 'style4',
                    showLensInfo: false,
                    showDateTime: false
                  })
                } else {
                  setWatermark({
                    ...watermark,
                    watermarkStyle: style.value as 'style1' | 'style2' | 'style3' | 'style4'
                  })
                }
              }}
              title={style.description}
            >
              <div className={componentStyles.styleThumbnail}>
                <PreviewComponent />
              </div>
              <div className={componentStyles.styleName}>{style.label}</div>
            </div>
          )
        })}
      </div>
    )
  }

  // 创建品牌logo选择器
  const renderBrandSelector = () => {
    return (
      <div className={componentStyles.watermarkStyleSelector} style={{ marginBottom: 12 }}>
        {brands.map((brand) => (
          <div
            key={brand.value}
            className={`${componentStyles.styleOption} ${
              watermark.brand === brand.value ? componentStyles.styleOptionActive : ''
            }`}
            onClick={() => setWatermark({ ...watermark, brand: brand.value })}
            title={brand.label}
          >
            <div className={componentStyles.styleThumbnail}>
              {brand.logo ? (
                <img
                  src={brand.logo}
                  alt={brand.label}
                  style={{ width: 40, height: 40, objectFit: 'contain' }}
                />
              ) : (
                <span style={{ color: '#bbb', fontSize: 18 }}>无</span>
              )}
            </div>
            <div className={componentStyles.styleName}>{brand.label}</div>
          </div>
        ))}
      </div>
    )
  }

  // 渲染参数设置面板
  const renderExifPanel = () => {
    return (
      <div className={styles.tabContent}>
        <div className={styles.exifControls}>
          {/* 新增机型输入框 */}
          <div>
            <label>
              <input
                type="checkbox"
                checked={!!watermark.showModel}
                onChange={(e) => setWatermark((w) => ({ ...w, showModel: e.target.checked }))}
              />{' '}
              显示机型
            </label>
            <input
              type="text"
              value={watermark.exifData.model}
              onChange={(e) =>
                setWatermark({
                  ...watermark,
                  exifData: { ...watermark.exifData, model: e.target.value }
                })
              }
            />
          </div>

          <div>
            <label>
              <input
                type="checkbox"
                checked={!!watermark.showAperture}
                onChange={(e) => setWatermark((w) => ({ ...w, showAperture: e.target.checked }))}
              />{' '}
              显示光圈
            </label>
            <input
              type="text"
              value={watermark.exifData.aperture}
              onChange={(e) =>
                setWatermark({
                  ...watermark,
                  exifData: { ...watermark.exifData, aperture: e.target.value }
                })
              }
            />
          </div>

          <div>
            <label>
              <input
                type="checkbox"
                checked={!!watermark.showShutter}
                onChange={(e) => setWatermark((w) => ({ ...w, showShutter: e.target.checked }))}
              />{' '}
              显示快门
            </label>
            <input
              type="text"
              value={watermark.exifData.shutterSpeed}
              onChange={(e) =>
                setWatermark({
                  ...watermark,
                  exifData: { ...watermark.exifData, shutterSpeed: e.target.value }
                })
              }
            />
          </div>

          <div>
            <label>
              <input
                type="checkbox"
                checked={!!watermark.showISO}
                onChange={(e) => setWatermark((w) => ({ ...w, showISO: e.target.checked }))}
              />{' '}
              显示ISO
            </label>
            <input
              type="text"
              value={watermark.exifData.iso}
              onChange={(e) =>
                setWatermark({
                  ...watermark,
                  exifData: { ...watermark.exifData, iso: e.target.value }
                })
              }
            />
          </div>

          <div>
            <label>
              <input
                type="checkbox"
                checked={!!watermark.showFocalLength}
                onChange={(e) => setWatermark((w) => ({ ...w, showFocalLength: e.target.checked }))}
              />{' '}
              显示焦距
            </label>
            <input
              type="text"
              value={watermark.exifData.focalLength}
              onChange={(e) =>
                setWatermark({
                  ...watermark,
                  exifData: { ...watermark.exifData, focalLength: e.target.value }
                })
              }
            />
          </div>

          <div>
            <label>
              <input
                type="checkbox"
                checked={!!watermark.showLensInfo}
                onChange={(e) => setWatermark((w) => ({ ...w, showLensInfo: e.target.checked }))}
              />{' '}
              显示镜头信息
            </label>
            <input
              type="text"
              value={watermark.lensInfo}
              onChange={(e) =>
                setWatermark({
                  ...watermark,
                  lensInfo: e.target.value
                })
              }
            />
          </div>

          <div>
            <label>
              <input
                type="checkbox"
                checked={!!watermark.showDateTime}
                onChange={(e) => setWatermark((w) => ({ ...w, showDateTime: e.target.checked }))}
              />{' '}
              显示拍摄日期
            </label>
            <input
              type="text"
              value={watermark.dateTime}
              onChange={(e) =>
                setWatermark({
                  ...watermark,
                  dateTime: e.target.value
                })
              }
            />
          </div>
        </div>
      </div>
    )
  }

  return (
    <>
      <SEO
        title="水印工具 - Zusheng Studio"
        description="给你的照片添加专业水印"
        keywords="Zusheng,水印,照片编辑,相机水印,徕卡,索尼,大疆,佳能,富士"
        url="https://zusheng.cc/lab/watermark"
      />
      <div className={styles.pageLab}>
        <div className={styles.container}>
          {/* 预览区在左侧 */}
          <div className={styles.previewArea}>
            {image ? (
              renderWatermark()
            ) : (
              <div className={styles.emptyState}>
                <p>请上传一张图片来添加水印</p>
              </div>
            )}
          </div>
          {/* 控制面板区域在右侧 */}
          <div className={styles.controlsArea}>
            <div className={styles.btnRow}>
              <label className={styles.uploadBtn}>
                <input
                  type="file"
                  accept="image/*"
                  onChange={handleImageUpload}
                  style={{ display: 'none' }}
                />
                选择图片
              </label>
              <div className={styles.uploadTip}>图片大小限制：50MB以内</div>
              <button
                className={styles.exportBtn}
                type="button"
                onClick={handleExport}
                disabled={!image}
              >
                导出图片
              </button>
            </div>
            {/* 水印样式选择器 - 缩略图形式 */}
            <div className={styles.watermarkStylePreview}>
              <h3>选择水印样式</h3>
              {renderStyleSelector()}
            </div>
            {/* 直接合并所有设置项，无tab切换 */}
            <div className={styles.styleSelector}>
              {/* 外观设置面板 */}
              <div className={styles.sectionBlock}>
                <div className={styles.sectionTitle}>外观设置</div>
                <div className={styles.tabContent}>
                  {/* style1 或 style2 显示背景色 */}
                  {(watermark.watermarkStyle === 'style1' ||
                    watermark.watermarkStyle === 'style2' ||
                    watermark.watermarkStyle === 'style4') && (
                    <div>
                      <label>背景颜色:</label>
                      <div
                        className={`${componentStyles.watermarkStyleSelector} ${styles.watermarkStyleSelector}`}
                        style={{ marginBottom: 12 }}
                      >
                        {backgroundColors.map((color) => (
                          <div
                            key={color.value}
                            className={`${componentStyles.styleOption} ${
                              watermark.backgroundColor === color.value
                                ? componentStyles.styleOptionActive
                                : ''
                            }`}
                            onClick={() =>
                              setWatermark({ ...watermark, backgroundColor: color.value })
                            }
                            title={color.label}
                          >
                            <div
                              className={componentStyles.styleThumbnail}
                              style={{ backgroundColor: color.value }}
                            >
                              <span
                                style={{
                                  color:
                                    color.value === 'white' || color.value === '#f5f5f5'
                                      ? '#333'
                                      : '#fff'
                                }}
                              >
                                Aa
                              </span>
                            </div>
                            <div className={componentStyles.styleName}>{color.label}</div>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                  <div className={styles.appearanceControls}>
                    {/* 字体大小百分比滑块，所有样式通用 */}
                    <div>
                      <label>字体大小:</label>
                      <input
                        type="range"
                        min="0.5"
                        max="2"
                        step="0.01"
                        value={fontSizeRatio}
                        onChange={(e) => setFontSizeRatio(Number(e.target.value))}
                      />
                      <span>{Math.round(fontSizeRatio * 100)}%</span>
                    </div>
                    {/* style1 或 style2 显示logo大小滑块 */}
                    {(watermark.watermarkStyle === 'style1' ||
                      watermark.watermarkStyle === 'style2' ||
                      watermark.watermarkStyle === 'style4') && (
                      <div>
                        <label>Logo大小:</label>
                        <input
                          type="range"
                          min="0.5"
                          max="2"
                          step="0.01"
                          value={logoSizeRatio}
                          onChange={(e) => setLogoSizeRatio(Number(e.target.value))}
                        />
                        <span>{Math.round(logoSizeRatio * 100)}%</span>
                      </div>
                    )}
                    {/* style2 或 style3 显示边距滑块 */}
                    {(watermark.watermarkStyle === 'style2' ||
                      watermark.watermarkStyle === 'style3' ||
                      watermark.watermarkStyle === 'style4') && (
                      <div>
                        <label>边距:</label>
                        <input
                          type="range"
                          min="0"
                          max="4"
                          step="0.1"
                          value={paddingEm}
                          onChange={(e) => setPaddingEm(Number(e.target.value))}
                        />
                        <span>{Math.round((paddingEm / 4) * 100)}%</span>
                      </div>
                    )}
                  </div>
                </div>
              </div>
              {/* 品牌logo选择器 */}
              <div className={styles.sectionBlock}>
                <div className={styles.sectionTitle}>品牌选择</div>
                <div className={styles.tabContent}>{renderBrandSelector()}</div>
              </div>
              {/* 参数设置面板 */}
              <div className={styles.sectionBlock}>
                <div className={styles.sectionTitle}>参数设置</div>
                {renderExifPanel()}
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  )
}

export default WaterMark
